import folium
import geocoder
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .forms import SearchForm
from .models import Search


def index(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(to='index')
    else:
        form = SearchForm()
    # Create Map Object
    m = folium.Map(location=[19, -12], zoom_start=2)
    address = Search.objects.all()
    # 地图上展示所有address
    for address in address:
        location = geocoder.osm(address)
        lat,lng = location.lat,location.lng
        # lng = location.lng
        country = address.address
        if lat is None or lng is None:
            address.delete()
            return HttpResponse('You address input is invalid')
        folium.Marker((lat, lng), tooltip='Click for more',popup=country,draggable=True).add_to(m)
    m = m._repr_html_()
    context = {
        'm': m,
        'form': form,
    }
    return render(request, 'map.html', context)
